package com.fenxiangle.yueding.feature.focus.view;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.fenxiangle.yueding.R;
import com.fenxiangle.yueding.common.alipay.PayResult;
import com.fenxiangle.yueding.common.widget.popupwindow.PayPopupWindow;
import com.fenxiangle.yueding.entity.bo.AliPayBo;
import com.fenxiangle.yueding.entity.bo.ExtensionBo;
import com.fenxiangle.yueding.feature.extension.contract.ExtensionContract;
import com.fenxiangle.yueding.feature.extension.login.DaggerExtensionComponent;
import com.fenxiangle.yueding.feature.extension.login.ExtensionPresenterModule;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.MD5Util;
import com.suozhang.framework.utils.T;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by Home on 2018/9/1.
 */

public class WithdrawDepositActivity extends BaseActivity implements ExtensionContract.View {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.wi_right)
    ImageView wiRight;
    @BindView(R.id.bank_name)
    TextView bankName;
    @BindView(R.id.bank_time)
    TextView bankTime;
    @BindView(R.id.wi_money)
    EditText wiMoney;
    @BindView(R.id.wi_balance)
    TextView wiBalance;
    @BindView(R.id.btn_all)
    TextView btnAll;
    @BindView(R.id.btn_deposit)
    TextView btnDeposit;
    @BindView(R.id.check_alibb)
    CheckBox checkAlibb;
    @BindView(R.id.check_weichat)
    CheckBox checkWeichat;
    @BindView(R.id.pay_money_title)
    TextView payMoneyTitle;
    @BindView(R.id.tv_pay_type_title)
    TextView tvPayTypeTitle;
    @BindView(R.id.show_tv)
    TextView tvShowTips;
    private int commissionType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_withdraw_deposit;
    }


    @Inject
    ExtensionContract.Presenter presenter;

    @Override
    protected void initInjector() {
        DaggerExtensionComponent.builder().extensionPresenterModule(new ExtensionPresenterModule(this)).build().inject(this);
    }

    String payType="0";
    String pay = "";
    String type="";
    String extensionBo="";
    @Override
    protected void initData() {
        commissionType=getIntent().getIntExtra("commissionType",0);
        pay = getIntent().getStringExtra("pay");
        type = getIntent().getStringExtra("type");
        if (!TextUtils.isEmpty(pay)&&pay.equals("1")){
            tvShowTips.setVisibility(View.GONE);
        }
        extensionBo = getIntent().getStringExtra("extensionBo");
        initToolBar(toolbar, TextUtils.isEmpty(pay) ? "提现" : "支付", true, true);
        if (!TextUtils.isEmpty(pay)) {
            payMoneyTitle.setText("输入支付金额");
            tvPayTypeTitle.setText("请选择支付方式");
            wiMoney.setHint("请输入支付金额");
            btnDeposit.setText("立即支付");
            wiBalance.setVisibility(View.GONE);
            if(type.equals("0")){
                wiMoney.setText("3000");
                wiMoney.setFocusable(false);
                wiMoney.setFocusableInTouchMode(false);
            }else{
                wiMoney.setText("300");
                wiMoney.setFocusable(false);
                wiMoney.setFocusableInTouchMode(false);
            }
        } else {
            wiBalance.setVisibility(View.VISIBLE);
            wiBalance.setText("账户余额￥"+extensionBo);

        }
    }

    @OnClick({R.id.check_alibb, R.id.check_weichat, R.id.btn_deposit,R.id.layout_alibb,R.id.layout_weichat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.check_alibb:
                checkAlibb.setChecked(true);
                checkWeichat.setChecked(false);
                payType = "0";
                break;
            case R.id.check_weichat:
                checkAlibb.setChecked(false);
                checkWeichat.setChecked(true);
                payType = "1";
                break;
            case  R.id.layout_alibb:
                checkAlibb.setChecked(true);
                checkWeichat.setChecked(false);
                payType = "0";
                break;
            case R.id.layout_weichat:
                checkAlibb.setChecked(false);
                checkWeichat.setChecked(true);
                payType = "1";
                break;
            case R.id.btn_deposit:
                if (TextUtils.isEmpty(wiMoney.getText().toString())) {
                    T.showShort("请输入提现金额");
                    return;
                }
                if (TextUtils.isEmpty(payType)) {
                    T.showShort("请选择提现方式");
                    return;
                }
                //充值
                if(!TextUtils.isEmpty(pay)&&pay.equals("1")){
                    JSONObject jsonObject=new JSONObject();
                    try {
                        jsonObject.put("transactionamount",wiMoney.getText().toString());
                        jsonObject.put("type",type);
                        jsonObject.put("payStatus",payType);
                        presenter.recharge_member(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }else{
                    //提现
                    presenter.is_set_pwd();

                }
                break;
        }
    }

    @Override
    public void ShowData(ExtensionBo s) {

    }

    /**
     * 检测是否安装支付宝
     *
     * @param context
     * @return
     */
    public static boolean checkAliPayInstalled(Context context) {

        Uri uri = Uri.parse("alipays://platformapi/startApp");
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        ComponentName componentName = intent.resolveActivity(context.getPackageManager());
        return componentName != null;
    }


    public void starAliPay(final String orderInfo) {
//        if (!checkAliPayInstalled(this)) {
//            T.showShort("未安装支付宝");
//            return;
//        }
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(WithdrawDepositActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();


    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);

                    Log.e("", "支付结果：" + payResult.getResultStatus() + "|" + payResult.getResult() + "|" + payResult.getMemo());

                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    /**
                     * 9000:订单支付成功
                     * 8000:正在处理中
                     * 4000:订单支付失败
                     * 6001:用户中途取消
                     * 6002:网络连接出错
                     * 6004:支付结果未知
                     */
                    Bundle bundle = new Bundle();
//                    HJApplication.getInstance().removeActivity();
                    if (TextUtils.equals(resultStatus, "9000")) {

                        Intent intent=new Intent();
                        intent.putExtra("alibb","1");
                        setResult(30000,intent);
                        finish();
//                        Intent intent = new Intent(activity, SuccOrErrorActivity.class);
//                        intent.putExtra("type","pay");
//                        startActivity(intent);
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                        Toast.makeText(context, "支付成功", Toast.LENGTH_SHORT).show();
//                        bundle.putInt(HJConstant.PAY_RESULT_STATE, HJConstant.PAY_SUCCESS_VALUE);
                    } else if(TextUtils.equals(resultStatus, "6001")){
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        T.showShort("用户中途取消");
                    }else if(TextUtils.equals(resultStatus, "4000")){
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        T.showShort("订单支付失败");
                    }else if(TextUtils.equals(resultStatus, "6002")){
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        T.showShort( "网络连接出错");
                    }else if(TextUtils.equals(resultStatus, "6004")){
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        T.showShort("支付结果未知");
                    }


//                    TurnUtil.openActivity(context, FoodsOrderSuccessActivity.class, bundle, false);
                    break;
                }

                default:
                    break;
            }
        }
    };

    @Override
    public void showLoginSuccess() {
        T.showShort("充值成功");
        finish();
    }
    private void toWxPay(AliPayBo wxPayBo) {
        IWXAPI api = WXAPIFactory.createWXAPI(this, wxPayBo.getWxpay_url().getAppid());
        api.registerApp(wxPayBo.getWxpay_url().getAppid());
        PayReq req = new PayReq();
        req.appId = wxPayBo.getWxpay_url().getAppid();
        req.partnerId = wxPayBo.getWxpay_url().getPartnerid();
        req.prepayId = wxPayBo.getWxpay_url().getPrepayid();
        req.nonceStr = wxPayBo.getWxpay_url().getNoncestr();
        req.timeStamp = wxPayBo.getWxpay_url().getTimestamp();
        req.packageValue = "Sign=WXPay";
        req.sign = wxPayBo.getWxpay_url().getSign();
        api.sendReq(req);
    }
    @Override
    public void showAliPayBo(AliPayBo aliPayBo) {
        if(aliPayBo!=null){
            if(payType.equals("0")){
                starAliPay(aliPayBo.getAlipay_url());
            }else{
                toWxPay(aliPayBo);
            }
        }else{
            T.showShort("获取失败");
        }
    }

    @Override
    public void showWeiChatData(AliPayBo aliPayBo) {
        if(aliPayBo!=null&&aliPayBo.getStatus()==1){
            Intent intent=new Intent(this,BindWeChatActivity.class);
            startActivityForResult(intent,30005);
        }else{
            Intent intent=new Intent();
            intent.putExtra("alibb","111");
            setResult(30000,intent);
            finish();
        }
    }

    @Override
    public void showError(String error) {
        T.showShort(error);
    }
    String pwdll="";
    @Override
    public void showPwd(String pwd) {
        if(!TextUtils.isEmpty(pwd)){
            if(pwd.equals("0")){//表示 没有设置支付密码
                PayPopupWindow payPopupWindow=new PayPopupWindow(this);
                payPopupWindow.showMoreWindow(btnDeposit,"请设置支付密码", new PayPopupWindow.PopupWindowListener() {
                    @Override
                    public void payPassWord(String passEord) {
                        T.showShort("密码设置成功");
                        JSONObject jsonObject=new JSONObject();
                        try {
                            pwdll =MD5Util.md5(passEord);
                            jsonObject.put("paymentPwd", pwdll);
                            presenter.user_payment_set(jsonObject);//设置支付密码
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }


                    }
                });
            }else{
                PayPopupWindow payPopupWindow=new PayPopupWindow(this);
                payPopupWindow.showMoreWindow(btnDeposit,"请输入支付密码", new PayPopupWindow.PopupWindowListener() {
                    @Override
                    public void payPassWord(String passEord) {
                        pwdll =MD5Util.md5(passEord);
                        if(payType.equals("0")){
                            Intent intent=new Intent(WithdrawDepositActivity.this,AlibbActivity.class);
                            intent.putExtra("pwdll",pwdll);
                            intent.putExtra("money",wiMoney.getText().toString());
                            intent.putExtra("commissionType",commissionType);
                            startActivityForResult(intent,30002);
                        }else{
                            JSONObject jsonObject=new JSONObject();
                            try {
                                jsonObject.put("transactionMount",wiMoney.getText().toString());
                                jsonObject.put("forwardType",payType);
                                jsonObject.put("commissionType",commissionType);
                                jsonObject.put("paymentPwd",pwdll);
                                presenter.user_forward(jsonObject);//微信提现 先调用提现 没有绑定 先绑定在调用提现
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
//                            T.showShort("暂未开通");
                        }
                    }
                });

            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 30002:
                if(data!=null&&!TextUtils.isEmpty(data.getStringExtra("alibb"))){
                    Intent intent=new Intent();
                    intent.putExtra("alibb","111");
                    setResult(30000,intent);
                    finish();
                }
                break;
            case 30005:
                if(data!=null&&!TextUtils.isEmpty(data.getStringExtra("openid"))){
                    try {
                        JSONObject jsonObject=new JSONObject();
                        jsonObject.put("openId",data.getStringExtra("openid"));
                        jsonObject.put("transactionMount",wiMoney.getText().toString());
                        jsonObject.put("forwardType",payType);
                        jsonObject.put("paymentPwd",pwdll);
                        presenter.user_forward(jsonObject);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }

    @Override
    public void user_payment_set() {
        if(payType.equals("0")){
            Intent intent=new Intent(WithdrawDepositActivity.this,AlibbActivity.class);
            intent.putExtra("pwdll",pwdll);
            intent.putExtra("money",wiMoney.getText().toString());
            startActivityForResult(intent,30002);
        }else{
            try {
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("transactionMount",wiMoney.getText().toString());
                jsonObject.put("forwardType",payType);
                jsonObject.put("paymentPwd",pwdll);
                presenter.user_forward(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
